<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 400px;
            height: 400px;
            border: 1px solid #000;
            position: relative;

        }

        span {
            display: none;
            position: absolute;
            top: 0;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: rgb(243, 91, 91);
        }
    </style>
</head>

<body>
    <div class="box">
        <span></span>
    </div>
    <script>
        var div = document.querySelector("div");
        var span = document.querySelector("span");
        // 1. 
        div.onmouseenter = function () {
            span.style.display = "block";
            div.onmousemove = function (e) {
                var x = div.getBoundingClientRect().x;// 标签距离浏览器
                var y = div.getBoundingClientRect().y;

                var l = e.clientX - x - span.offsetWidth / 2;//鼠标到标签
                var t = e.clientY - y - span.offsetHeight / 2;

                l = l < 0 ? 0 : l;
                t = t < 0 ? 0 : t;

                var maxW = div.offsetWidth - span.offsetWidth;
                var maxH = div.offsetHeight - span.offsetHeight;

                l = l > maxW ? maxW : l;
                t = t > maxH ? maxH : t;

                span.style.left = l + "px";
                span.style.top = t + "px";

            }
        }
        div.onmouseleave = function () {
            span.style.display = "none";
            div.onmousemove = null;
        }
    </script>
</body>

</html>